package com.aaa.fees.service.ipml;

import com.aaa.entity.Charge;
import com.aaa.fees.dao.ChargeDao;
import com.aaa.fees.service.ChargeService;
import com.aaa.fees.utils.HttpClient;
import com.aaa.fees.vo.ChargeVo;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class ChargeServiceImpl implements ChargeService {
    @Autowired
    ChargeDao chargeDao;
    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result<IPage<Charge>> getinfocharge(Integer currentPage, Integer pageSize, ChargeVo chargeVo) {
        IPage<Charge> page=new Page<>(currentPage,pageSize);
        QueryWrapper<Charge> wrapper=new QueryWrapper<>();
        if(StringUtils.hasText(chargeVo.getRegId())){
            wrapper.like("reg_id", chargeVo.getRegId());
        }
        if(StringUtils.hasText(chargeVo.getPatientName())){
            wrapper.like("patient_name", chargeVo.getPatientName());
        }

        IPage<Charge> page1 = chargeDao.selectPage(page, wrapper);
        return new Result<IPage<Charge>>(200,"查询用户成功",page1);
    }
    //微信
    @Override
    public Result createNavite(String orderId) {
        //1.根据订单号查询出订单信息
        QueryWrapper<Charge> wrapper=new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        wrapper.eq("order_status",0);
        Charge orderCharge = chargeDao.selectOne(wrapper);
        System.out.println("数据为："+orderCharge);
        if (orderCharge!=null){
            System.out.println("数据为："+orderCharge);
            try {
                //设置请求的参数
                Map<String, String> params = new HashMap<>();//请求参数
                params.put("appid", appId);
                params.put("mch_id", mchId);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", orderCharge.getPatientName());//标题
                params.put("out_trade_no", orderId);
                //支付金额0.01 未来换成真是的金额
                params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
                params.put("spbill_create_ip", "127.0.0.1");//未来写成项目部署的ip
                params.put("notify_url", "http:localhost:8080/fees/api/charge/infocharge");
                params.put("trade_type", "NATIVE");
                //创建httpClient对象 作用远程调用
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //支持https协议
                client.setHttps(true);
                //设置请求参数
                client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
                //发送请求
                client.post();
                //获取请求的响应结果
                String content = client.getContent();

                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if (map.get("result_code").equals("SUCCESS")){
                    Map<String,Object> result=new HashMap<>();
                    result.put("codeUrl",map.get("code_url"));
                    result.put("price",orderCharge.getOrderAmount());
                    result.put("orderId",orderId);
                    return new Result(200,"生成二维码成功",result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return new Result(200,"订单失效了",null);
    }
    //根据订单查询支付状态
    @Override
    public Result queryPayStatus(String orderId) {
        Boolean flag=false;
        try {
            //根据订单状态查询微信的支付的状态
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("out_trade_no", orderId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
            client.post();
            String content = client.getContent();
            System.out.println(content);
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("trade_state").equals("SUCCESS")){
                flag=true;
                //1修改订单状态
                Charge order=new Charge();
                order.setOrderStatus("1");
                order.setPayType("1");
                QueryWrapper<Charge> wrapper=new QueryWrapper<>();
                wrapper.eq("order_id",orderId);
                wrapper.eq("order_status",0);
                chargeDao.update(order,wrapper);
                return  new Result(200,"支付成功",flag);
            }
        }catch (Exception e){

        }

        return  new Result(200,"请扫码二维码支付",flag);
    }

}
